import time
import traceback
from datetime import datetime
from dataflow.conf import notify_emails

import pymysql

from common.exchange_mail_util import ExchangeUtil
from dataflow.conf import database_conf
from dataflow.score_util import get_calc_score
from common.logger import Logger
db = pymysql.connect(**database_conf['imei_database'])
cursor = db.cursor()

logger = Logger("update_score.log").getLogger()

while 1:
    try:
        start_time = time.time()
        cursor.execute("select imei, apply_time from imei_score where is_update=0 ")
        result = cursor.fetchall()
        sql_time = time.time()
        sql_cost_time = (sql_time - start_time) * 1000
        logger.info('update_score while sql cost ' + str(int(sql_cost_time)))

        if len(result) == 0:
            time.sleep(10)

        for row in result:
            imei = row[0]
            apply_time = row[1]
            score_app, score_input = get_calc_score(imei, apply_time)
            if score_app is not None and score_input is not None:
                logger.info(str(imei) + ' ' + str(apply_time) + ' ' + str(score_app) + ' ' + str(score_input))
                cursor.execute(
                    "update imei_score set score_app='%s', score_input='%s', is_update=1 WHERE imei = '%s' AND apply_time=%s " % (score_app, score_input, imei, apply_time))

        end_time = time.time()
        interval_time = (end_time - start_time)
        logger.info('update_score while cost ' + str(int(interval_time)))
    except KeyboardInterrupt as e:
        exit(-1)
    except Exception as e:
        logger.error(traceback.format_exc())
        mail = ExchangeUtil('imei分数更新脚本异常', notify_emails)
        mail.set_content(traceback.format_exc())
        mail.send()
        time.sleep(5)

